//
//  Celldetails.m
//  The_news
//
//  Created by 王&甄 on 15/7/17.
//  Copyright (c) 2015年 chenlin. All rights reserved.
//

#import "Celldetails.h"
#import "CelldetailsModel.h"
#import "CellPicsModel.h"
#import "NewsModel.h"
#import "NetWorkTools.h"
#import "AFNetworking.h"
@interface Celldetails ()<UIWebViewDelegate>
@property(nonatomic, retain)CelldetailsModel *detailsModel;
@property(nonatomic, retain)CellPicsModel *picModel;
@property(nonatomic, retain)NSArray *news;
@property(nonatomic, retain)UIWebView *web;
@property(nonatomic, retain)NewsModel *newsModel;

@end

@implementation Celldetails
//- (void)dealloc
//{
//    [super dealloc];
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
   
    
    self.web.delegate  =self;
    self.view.backgroundColor = [UIColor whiteColor];
    self.web = [[UIWebView alloc]init];
    self.web.frame = [UIScreen mainScreen].bounds;
//    //web自适应
//    self.web.scalesPageToFit = YES;
    [self.web.scrollView setContentInset:UIEdgeInsetsMake(60,0 , 0, 0)];
    [self.web.scrollView setBounces:NO];
//    [web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.cellString]]];
    [self.view addSubview:self.web];
    

    CGRect rectheaderL = CGRectMake(0, -20, self.view.frame.size.width, 84);
    UIView *headerl = [[UIView alloc]init];
    headerl.frame = rectheaderL;
//    headerl.backgroundColor = [UIColor grayColor];
    headerl.backgroundColor = [UIColor colorWithRed:19 / 255.0 green:158 / 255.0 blue:238 / 255.0 alpha:1];
    [self.view addSubview:headerl];
    [headerl release];
       self.automaticallyAdjustsScrollViewInsets = YES;
    
    UIView *view = [[UIView alloc]init];
    view.center = CGPointMake([UIScreen mainScreen].bounds.origin.x, 30);
    view.backgroundColor = [UIColor clearColor];
    view.frame = CGRectMake(self.view.frame.size.width / 2 - 50, 40, 100, 40);
    
    
    UILabel *lable1 = [[UILabel alloc]initWithFrame:view.bounds];
    lable1.backgroundColor = [UIColor clearColor];
    lable1.text = @"新闻详情";
 //   [lable1 sizeToFit];
    lable1.textAlignment = NSTextAlignmentCenter;
    [lable1 setFont:[UIFont boldSystemFontOfSize:20]];
    [view addSubview:lable1];
    
    [headerl addSubview:view];

//    self.navigationController.navigationBar.barStyle = UIStatusBarStyleDefault;
//    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
//
//    self.title = @"新闻详情";
    
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.backgroundColor = [UIColor clearColor];
<<<<<<< HEAD
    button.frame = CGRectMake(15, 50, 25, 25);
    [button setImage:[UIImage imageNamed:@"fanhui"] forState:UIControlStateNormal];
    [headerl addSubview:button];
    [button addTarget:self action:@selector(Action) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *buttonShare = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonShare.backgroundColor = [UIColor clearColor];
    buttonShare.frame = CGRectMake(WIDTH - 40, 50, 25, 25);
    [buttonShare setImage:[UIImage imageNamed:@"fenxiang"] forState:UIControlStateNormal];
    [headerl addSubview:buttonShare];
    [buttonShare addTarget:self action:@selector(share) forControlEvents:UIControlEventTouchUpInside];


    
=======
    button.frame = CGRectMake(0, 40, 60, 40);
    [button setTitle:@"返回" forState:UIControlStateNormal];
    [headerl addSubview:button];
    [button addTarget:self action:@selector(Action) forControlEvents:UIControlEventTouchUpInside];
>>>>>>> 5aabf5f3ed3bf002994c076f8caa1ea0a394d1cf
//     Do any additional setup after loading the view.
//数据加载
    
    
    NSString *url = [NSString stringWithFormat:@"http://c.m.163.com/nc/article/%@/full.html",self.docidd];
    NSString *lurl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
   

    
    // http://c.m.163.com/nc/article/AUN0BNND0001124J/full.html
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    manger.responseSerializer = [AFJSONResponseSerializer serializer];
    [manger.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/css", @"text/plain", nil] ];
    [manger GET:lurl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            
            self.detailsModel = [CelldetailsModel cellDetailsWithdic:responseObject[self.docidd]];
            
            [self showWeb];
        }else{
            NSLog(@"error");
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"failed");
    }];
    
}
- (void)Action{
    [self dismissViewControllerAnimated:NO completion:^{
        
    }];
}
- (NSArray *)news{
    if (_news == nil) {
        _news = [NSArray array];
        _news = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"NewsURLs.plist" ofType:nil]];
    }
    return _news;
}

- (void)showWeb{
    NSMutableString *html = [NSMutableString string];
    [html appendString:@"<html>"];
    [html appendString:@"<head>"];
    [html appendFormat:@"<link rel=\"stylesheet\" href=\"%@\">",[[NSBundle mainBundle] URLForResource:@"SXDetails.css" withExtension:nil]];
    [html appendString:@"</head>"];
    
    [html appendString:@"<body>"];
    [html appendString:[self touchBody]];
    [html appendString:@"</body>"];
    
    [html appendString:@"</html>"];
    
    [self.web loadHTMLString:html baseURL:nil];
    
}
- (NSString *)touchBody
{
    NSMutableString *body = [NSMutableString string];
    [body appendFormat:@"<div class=\"title\">%@</div>",self.detailsModel.title];
    [body appendFormat:@"<div class=\"time\">%@</div>",self.detailsModel.ptime];
    if (self.detailsModel.body != nil) {
        [body appendString:self.detailsModel.body];
    }
    // 遍历img
    for (CellPicsModel *detailImgModel in self.detailsModel.img) {
        NSMutableString *imgHtml = [NSMutableString string];
        
        // 设置img的div
        [imgHtml appendString:@"<div class=\"img-parent\">"];
        
        // 数组存放被切割的像素
        NSArray *pixel = [detailImgModel.pixel componentsSeparatedByString:@"*"];
        CGFloat width = [[pixel firstObject]floatValue];
        CGFloat height = [[pixel lastObject]floatValue];
        // 判断是否超过最大宽度
        CGFloat maxWidth = [UIScreen mainScreen].bounds.size.width * 0.96;
        if (width > maxWidth) {
            height = maxWidth / width * height;
            width = maxWidth;
        }
        
        NSString *onload = @"this.onclick = function() {"
        "  window.location.href = 'sx:src=' +this.src;"
        "};";
        [imgHtml appendFormat:@"<img onload=\"%@\" width=\"%f\" height=\"%f\" src=\"%@\">",onload,width,height,detailImgModel.src];
        // 结束标记
        [imgHtml appendString:@"</div>"];
        // 替换标记
        [body replaceOccurrencesOfString:detailImgModel.ref withString:imgHtml options:NSCaseInsensitiveSearch range:NSMakeRange(0, body.length)];
    }
    return body;
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *url = request.URL.absoluteString;
    NSRange range = [url rangeOfString:@"sx:src="];
    if (range.location != NSNotFound) {
        NSInteger begin = range.location + range.length;
        NSString *src = [url substringFromIndex:begin];
        return NO;
    }
    return YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
